﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Coding4Fun.Chair.Cockpit.Controls
{
    /// <summary>
    /// Interaction logic for WheelPowerMeter.xaml
    /// </summary>
    public partial class WheelPowerMeter : UserControl
    {
        readonly SolidColorBrush _defaultBrush;
        readonly List<Brush> _rectangleDefaultBrushes = new List<Brush>();
        readonly IEnumerable<Rectangle> _rectangles;

        readonly double _stepCount;

        //number from -1 (full reverse) to 1 (full forward)
        private double _power;
        public double Power
        {
            get { return _power; }
            set
            {
                _power = Utilities.KeepBounds(value, -1, 1); // checking bounds

                double ceiling = 1;
                var centerRectIndex = _rectangles.Count() / 2;
                var index = 0;

                foreach (var rect in _rectangles)
                {
                    if(index != centerRectIndex)
                        ceiling -= _stepCount;

                    if (index < centerRectIndex)
                    {
                        rect.Fill = Power > ceiling ? _rectangleDefaultBrushes[index] : _defaultBrush;
                    }
                    else if (index > centerRectIndex)
                    {
                        rect.Fill = Power < ceiling ? _rectangleDefaultBrushes[index] : _defaultBrush;
                    }

                    index++;
                }
            }
        }

        public WheelPowerMeter()
        {
            InitializeComponent();

            _defaultBrush =  new SolidColorBrush((Color)Resources["PowerNubDimColor"]);
            _rectangles = LayoutRoot.Children.OfType<Rectangle>();

            foreach (var child in _rectangles)
            {
                _rectangleDefaultBrushes.Add(child.Fill);
            }

            _stepCount = 2 / (double)_rectangles.Count();

            Power = 0;
        }
    }
}